package com.fary.beans;

import com.fary.core.MethodParameter;
import com.fary.core.SpringException;
import com.fary.core.convert.TypeDescriptor;
import com.fary.util.Assert;

import java.lang.reflect.Field;

public abstract class TypeConverterSupport extends PropertyEditorRegistrySupport implements TypeConverter {


    TypeConverterDelegate typeConverterDelegate;


    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType) throws SpringException {
        return convertIfNecessary(value, requiredType, TypeDescriptor.valueOf(requiredType));
    }

    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType, MethodParameter methodParam) throws SpringException {
        return convertIfNecessary(value, requiredType, (methodParam != null ? new TypeDescriptor(methodParam) : TypeDescriptor.valueOf(requiredType)));
    }

    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType, Field field) throws SpringException {
        return convertIfNecessary(value, requiredType, (field != null ? new TypeDescriptor(field) : TypeDescriptor.valueOf(requiredType)));
    }

    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType, TypeDescriptor typeDescriptor) throws SpringException {
        Assert.state(this.typeConverterDelegate != null, "No TypeConverterDelegate");
        try {
            return this.typeConverterDelegate.convertIfNecessary(null, null, value, requiredType, typeDescriptor);
        } catch (SpringException | IllegalStateException ex) {
            throw new SpringException(requiredType.getName(), ex);
        }
    }

}
